{% extends 'base.html' %}
{% load widget_tweaks %}
{% load static %}

{% block title %}{{ title }} - 博客管理{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/theme/monokai.min.css">
<style>
    .markdown-editor-container {
        border: 1px solid var(--border-color);
        border-radius: 8px;
        overflow: hidden;
        background: var(--card-bg);
    }
    
    .editor-toolbar {
        background: var(--bg-secondary);
        padding: 10px 15px;
        border-bottom: 1px solid var(--border-color);
        display: flex;
        gap: 10px;
        align-items: center;
    }
    
    .editor-btn {
        background: var(--primary-color);
        color: white;
        border: none;
        padding: 5px 10px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 12px;
        transition: all 0.3s ease;
    }
    
    .editor-btn:hover {
        background: var(--primary-hover);
        transform: translateY(-1px);
    }
    
    .editor-content {
        display: flex;
        height: 500px;
    }
    
    .editor-pane, .preview-pane {
        flex: 1;
        overflow: auto;
    }
    
    .preview-pane {
        border-left: 1px solid var(--border-color);
        padding: 20px;
        background: var(--bg-primary);
    }
    
    .CodeMirror {
        height: 100%;
        font-family: 'JetBrains Mono', monospace;
        font-size: 14px;
    }
    
    .form-section {
        background: var(--card-bg);
        border-radius: 12px;
        padding: 25px;
        margin-bottom: 20px;
        border: 1px solid var(--border-color);
    }
    
    .form-section h3 {
        color: var(--text-primary);
        margin-bottom: 20px;
        font-size: 1.2rem;
        font-weight: 600;
    }
    
    .form-row {
        display: flex;
        gap: 20px;
        margin-bottom: 20px;
    }
    
    .form-col {
        flex: 1;
    }
    
    .form-group {
        margin-bottom: 20px;
    }
    
    .form-label {
        display: block;
        margin-bottom: 8px;
        color: var(--text-primary);
        font-weight: 500;
    }
    
    .form-control, .form-select {
        width: 100%;
        padding: 12px 15px;
        border: 1px solid var(--border-color);
        border-radius: 8px;
        background: var(--bg-primary);
        color: var(--text-primary);
        font-size: 14px;
        transition: all 0.3s ease;
    }
    
    .form-control:focus, .form-select:focus {
        outline: none;
        border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
    }
    
    .tags-container {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 10px;
    }
    
    .tag-checkbox {
        display: flex;
        align-items: center;
        background: var(--bg-secondary);
        padding: 8px 12px;
        border-radius: 20px;
        border: 1px solid var(--border-color);
        cursor: pointer;
        transition: all 0.3s ease;
    }
    
    .tag-checkbox:hover {
        background: var(--primary-color);
        color: white;
    }
    
    .tag-checkbox input {
        margin-right: 8px;
    }
    
    .btn-group {
        display: flex;
        gap: 15px;
        justify-content: flex-end;
        margin-top: 30px;
    }
    
    .btn {
        padding: 12px 25px;
        border: none;
        border-radius: 8px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;
        text-decoration: none;
        display: inline-block;
        text-align: center;
    }
    
    .btn-primary {
        background: var(--primary-gradient);
        color: white;
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0, 123, 255, 0.3);
    }
    
    .btn-secondary {
        background: var(--bg-secondary);
        color: var(--text-primary);
        border: 1px solid var(--border-color);
    }
    
    .btn-secondary:hover {
        background: var(--bg-tertiary);
    }
    
    .preview-content {
        line-height: 1.8;
    }
    
    .preview-content h1, .preview-content h2, .preview-content h3,
    .preview-content h4, .preview-content h5, .preview-content h6 {
        color: var(--text-primary);
        margin: 20px 0 10px 0;
    }
    
    .preview-content p {
        margin-bottom: 15px;
        color: var(--text-secondary);
    }
    
    .preview-content pre {
        background: var(--bg-secondary);
        padding: 15px;
        border-radius: 8px;
        overflow-x: auto;
        margin: 15px 0;
    }
    
    .preview-content code {
        background: var(--bg-secondary);
        padding: 2px 6px;
        border-radius: 4px;
        font-family: 'JetBrains Mono', monospace;
    }
    
    .preview-content blockquote {
        border-left: 4px solid var(--primary-color);
        padding-left: 20px;
        margin: 20px 0;
        font-style: italic;
        color: var(--text-secondary);
    }
</style>
{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="gradient-text">{{ title }}</h1>
                <a href="{% url 'blog:article_list' %}" class="btn btn-secondary">
                    <i class="fas fa-arrow-left me-2"></i>返回列表
                </a>
            </div>
            
            {% if messages %}
                {% for message in messages %}
                    <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
                        {{ message }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                {% endfor %}
            {% endif %}
            
            <form method="post" enctype="multipart/form-data" id="articleForm">
                {% csrf_token %}
                
                <!-- 基本信息 -->
                <div class="form-section">
                    <h3><i class="fas fa-edit me-2"></i>基本信息</h3>
                    
                    <div class="form-group">
                        <label class="form-label" for="{{ form.title.id_for_label }}">{{ form.title.label }}</label>
                        {{ form.title|add_class:"form-control" }}
                        {% if form.title.errors %}
                            <div class="text-danger mt-1">{{ form.title.errors.0 }}</div>
                        {% endif %}
                    </div>
                    
                    <div class="form-row">
                        <div class="form-col">
                            <label class="form-label" for="{{ form.category.id_for_label }}">{{ form.category.label }}</label>
                            {{ form.category|add_class:"form-select" }}
                            {% if form.category.errors %}
                                <div class="text-danger mt-1">{{ form.category.errors.0 }}</div>
                            {% endif %}
                        </div>
                        <div class="form-col">
                            <label class="form-label" for="{{ form.status.id_for_label }}">{{ form.status.label }}</label>
                            {{ form.status|add_class:"form-select" }}
                            {% if form.status.errors %}
                                <div class="text-danger mt-1">{{ form.status.errors.0 }}</div>
                            {% endif %}
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="{{ form.excerpt.id_for_label }}">{{ form.excerpt.label }}</label>
                        {{ form.excerpt|add_class:"form-control" }}
                        {% if form.excerpt.errors %}
                            <div class="text-danger mt-1">{{ form.excerpt.errors.0 }}</div>
                        {% endif %}
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="{{ form.featured_image.id_for_label }}">{{ form.featured_image.label }}</label>
                        {{ form.featured_image|add_class:"form-control" }}
                        {% if form.featured_image.errors %}
                            <div class="text-danger mt-1">{{ form.featured_image.errors.0 }}</div>
                        {% endif %}
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">{{ form.tags.label }}</label>
                        <div class="tags-container">
                            {% for choice in form.tags %}
                                <label class="tag-checkbox">
                                    {{ choice.tag }}
                                    <span>{{ choice.choice_label }}</span>
                                </label>
                            {% endfor %}
                        </div>
                        {% if form.tags.errors %}
                            <div class="text-danger mt-1">{{ form.tags.errors.0 }}</div>
                        {% endif %}
                    </div>
                    
                    <div class="form-group">
                        <div class="form-check">
                            {{ form.is_featured|add_class:"form-check-input" }}
                            <label class="form-check-label" for="{{ form.is_featured.id_for_label }}">
                                {{ form.is_featured.label }}
                            </label>
                        </div>
                    </div>
                </div>
                
                <!-- 文章内容 -->
                <div class="form-section">
                    <h3><i class="fas fa-file-alt me-2"></i>文章内容</h3>
                    
                    <div class="form-group">
                        <label class="form-label" for="{{ form.content.id_for_label }}">{{ form.content.label }}</label>
                        <div class="markdown-editor-container">
                            <div class="editor-toolbar">
                                <button type="button" class="editor-btn" onclick="insertMarkdown('**', '**', '粗体文字')">
                                    <i class="fas fa-bold"></i> 粗体
                                </button>
                                <button type="button" class="editor-btn" onclick="insertMarkdown('*', '*', '斜体文字')">
                                    <i class="fas fa-italic"></i> 斜体
                                </button>
                                <button type="button" class="editor-btn" onclick="insertMarkdown('`', '`', '代码')">
                                    <i class="fas fa-code"></i> 代码
                                </button>
                                <button type="button" class="editor-btn" onclick="insertMarkdown('[', '](url)', '链接文字')">
                                    <i class="fas fa-link"></i> 链接
                                </button>
                                <button type="button" class="editor-btn" onclick="insertMarkdown('![', '](url)', '图片描述')">
                                    <i class="fas fa-image"></i> 图片
                                </button>
                                <button type="button" class="editor-btn" onclick="insertMarkdown('## ', '', '标题')">
                                    <i class="fas fa-heading"></i> 标题
                                </button>
                                <button type="button" class="editor-btn" onclick="insertMarkdown('> ', '', '引用文字')">
                                    <i class="fas fa-quote-right"></i> 引用
                                </button>
                                <button type="button" class="editor-btn" onclick="togglePreview()">
                                    <i class="fas fa-eye"></i> 预览
                                </button>
                            </div>
                            <div class="editor-content">
                                <div class="editor-pane">
                                    <textarea name="content" id="{{ form.content.id_for_label }}" 
                                              class="form-control markdown-editor" 
                                              rows="20" 
                                              placeholder="请输入文章内容，支持Markdown语法">{{ form.content.value|default:'' }}</textarea>
                                </div>
                                <div class="preview-pane" id="previewPane" style="display: none;">
                                    <div class="preview-content" id="previewContent">
                                        <p class="text-muted">点击预览按钮查看效果...</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% if form.content.errors %}
                            <div class="text-danger mt-1">{{ form.content.errors.0 }}</div>
                        {% endif %}
                    </div>
                </div>
                
                <div class="btn-group">
                    <a href="{% url 'blog:article_list' %}" class="btn btn-secondary">
                        <i class="fas fa-times me-2"></i>取消
                    </a>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>
                        {% if action == 'create' %}创建文章{% else %}更新文章{% endif %}
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/markdown/markdown.min.js"></script>
<script>
    let editor;
    let previewVisible = false;
    
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化CodeMirror编辑器
        const textarea = document.getElementById('{{ form.content.id_for_label }}');
        editor = CodeMirror.fromTextArea(textarea, {
            mode: 'markdown',
            theme: 'monokai',
            lineNumbers: true,
            lineWrapping: true,
            autoCloseBrackets: true,
            matchBrackets: true,
            indentUnit: 4,
            tabSize: 4,
            extraKeys: {
                "Ctrl-Space": "autocomplete",
                "Ctrl-/": "toggleComment",
                "Ctrl-S": function(cm) {
                    document.getElementById('articleForm').submit();
                }
            }
        });
        
        // 监听内容变化，实时更新预览
        editor.on('change', function() {
            if (previewVisible) {
                updatePreview();
            }
        });
    });
    
    /**
     * 插入Markdown语法
     */
    function insertMarkdown(prefix, suffix, placeholder) {
        const doc = editor.getDoc();
        const cursor = doc.getCursor();
        const selection = doc.getSelection();
        
        if (selection) {
            doc.replaceSelection(prefix + selection + suffix);
        } else {
            doc.replaceRange(prefix + placeholder + suffix, cursor);
            // 选中占位符文本
            const start = {line: cursor.line, ch: cursor.ch + prefix.length};
            const end = {line: cursor.line, ch: cursor.ch + prefix.length + placeholder.length};
            doc.setSelection(start, end);
        }
        
        editor.focus();
    }
    
    /**
     * 切换预览模式
     */
    function togglePreview() {
        const previewPane = document.getElementById('previewPane');
        const editorPane = document.querySelector('.editor-pane');
        
        if (previewVisible) {
            // 隐藏预览
            previewPane.style.display = 'none';
            editorPane.style.flex = '1';
            previewVisible = false;
        } else {
            // 显示预览
            previewPane.style.display = 'block';
            editorPane.style.flex = '1';
            previewVisible = true;
            updatePreview();
        }
    }
    
    /**
     * 更新预览内容
     */
    function updatePreview() {
        const content = editor.getValue();
        const previewContent = document.getElementById('previewContent');
        
        if (!content.trim()) {
            previewContent.innerHTML = '<p class="text-muted">暂无内容...</p>';
            return;
        }
        
        // 发送AJAX请求获取预览
        fetch('{% url "blog:markdown_preview" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            },
            body: JSON.stringify({
                content: content
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                previewContent.innerHTML = data.html;
            } else {
                previewContent.innerHTML = '<p class="text-danger">预览失败: ' + data.error + '</p>';
            }
        })
        .catch(error => {
            previewContent.innerHTML = '<p class="text-danger">预览失败: ' + error.message + '</p>';
        });
    }
    
    // 表单提交前同步编辑器内容并验证
    document.getElementById('articleForm').addEventListener('submit', function(e) {
        // 同步CodeMirror内容到textarea
        editor.save();
        
        // 获取内容并验证
        const content = editor.getValue().trim();
        if (!content) {
            e.preventDefault();
            showMessage('文章内容不能为空', 'error');
            return false;
        }
        
        return true;
    });
    
    /**
     * 处理图片粘贴功能
     */
    function handleImagePaste() {
        // 监听粘贴事件
        editor.on('paste', function(cm, event) {
            const clipboardData = event.clipboardData || event.originalEvent.clipboardData;
            if (!clipboardData) return;
            
            const items = clipboardData.items;
            for (let i = 0; i < items.length; i++) {
                const item = items[i];
                
                // 检查是否为图片
                if (item.type.indexOf('image') !== -1) {
                    event.preventDefault(); // 阻止默认粘贴行为
                    
                    const file = item.getAsFile();
                    if (file) {
                        uploadImageAndInsert(file);
                    }
                    break;
                }
            }
        });
        
        // 监听拖拽事件
        const editorElement = document.querySelector('.CodeMirror');
        
        editorElement.addEventListener('dragover', function(e) {
            e.preventDefault();
            e.stopPropagation();
            editorElement.classList.add('drag-over');
        });
        
        editorElement.addEventListener('dragleave', function(e) {
            e.preventDefault();
            e.stopPropagation();
            editorElement.classList.remove('drag-over');
        });
        
        editorElement.addEventListener('drop', function(e) {
            e.preventDefault();
            e.stopPropagation();
            editorElement.classList.remove('drag-over');
            
            const files = e.dataTransfer.files;
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                if (file.type.indexOf('image') !== -1) {
                    uploadImageAndInsert(file);
                }
            }
        });
    }
    
    /**
     * 上传图片并插入到编辑器
     */
    function uploadImageAndInsert(file) {
        // 显示上传进度
        const cursor = editor.getCursor();
        const uploadingText = `![上传中...](uploading-${Date.now()})`;
        editor.replaceRange(uploadingText, cursor);
        
        // 创建FormData
        const formData = new FormData();
        formData.append('image', file);
        formData.append('csrfmiddlewaretoken', document.querySelector('[name=csrfmiddlewaretoken]').value);
        
        // 上传图片
        fetch('{% url "blog:upload_image" %}', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 替换上传中的文本为实际图片链接
                const content = editor.getValue();
                const newContent = content.replace(uploadingText, `![${file.name}](${data.url})`);
                editor.setValue(newContent);
                
                // 更新预览
                if (previewVisible) {
                    updatePreview();
                }
                
                // 显示成功消息
                showMessage('图片上传成功！', 'success');
            } else {
                // 移除上传中的文本
                const content = editor.getValue();
                const newContent = content.replace(uploadingText, '');
                editor.setValue(newContent);
                
                showMessage('图片上传失败: ' + (data.error || '未知错误'), 'error');
            }
        })
        .catch(error => {
            // 移除上传中的文本
            const content = editor.getValue();
            const newContent = content.replace(uploadingText, '');
            editor.setValue(newContent);
            
            showMessage('图片上传失败: ' + error.message, 'error');
        });
    }
    
    /**
     * 显示消息提示
     */
    function showMessage(message, type) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show`;
        messageDiv.style.position = 'fixed';
        messageDiv.style.top = '20px';
        messageDiv.style.right = '20px';
        messageDiv.style.zIndex = '9999';
        messageDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(messageDiv);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (messageDiv.parentNode) {
                messageDiv.parentNode.removeChild(messageDiv);
            }
        }, 3000);
    }
    
    // 初始化图片粘贴功能
    handleImagePaste();
</script>
{% endblock %}